//
//  PlayerView.m
//  BroadcastTest
//
//  Created by zhaoxiaoyan on 16/12/1.
//  Copyright © 2016年 xiaoyanzhao. All rights reserved.
//

#import "PlayerView.h"

@interface PlayerView () {
    NSURL *_url;
}

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) AVPlayerItem *item;

@end

@implementation PlayerView

- (instancetype)initWithUrl:(NSURL *)url {
    self = [super init];
    if (self) {
        _url = url;
        [self setupPlayer];
    }
    return self;
}

- (instancetype)initWithURLAssert:(AVURLAsset *)assert {
    self = [super init];
    if (self) {
        self.assert = assert;
        [self setupPlayer];
    }
    return self;
}

- (void)setupPlayer {
    // 视频播放的主要类名
    // 1.AVPlayer 用于播放音视频
    // 2.AVPlayerItem 音频的对象
    // 3.AVPlayerLayer 播放显示视频的图层界面
    // 4.AVPlayerViewController 创建视频的图层,包含有调节控件
    
    // 视频播放的三个步骤
    // 1.第一部分是AVPlayer,视频播放器
    // 2.AVPlayerItem, 视频要播放的元素
    // 3.AVPlayerLayer, 视频现实的图层
    // 具体的流程是AVPlayer->AVPlayerItem->AVPlayerLayer
    
    // 1.创建需要播放的元素
//    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@".m4v"];
    self.item = [AVPlayerItem playerItemWithURL:_url];
    
    // 2.创建播放器
    self.player = [[AVPlayer alloc] init];
    self.player = [AVPlayer playerWithPlayerItem:self.item];
    
    // 3.创建视频显示的图层
    self.playerLayer = [[AVPlayerLayer alloc] init];
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.backgroundColor = [UIColor blackColor].CGColor;
    self.playerLayer.player = self.player;
    
    self.playerLayer.frame = CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 64);
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    
    [self.layer addSublayer:self.playerLayer];
    [self.layer insertSublayer:self.playerLayer atIndex:0];

    
}

- (void)play {
    [self.player play];
    
}

- (void)pause {
    [self.player pause];
}

- (void)stop {
    [self.player pause];
}


@end
